/*
 * =====================================================================================
 *
 *       Filename:  cl_timer_service.hxx
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  02/27/2011 06:01:02 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Ken Chen (Ken), chen_kenz@emc.com
 *        Company:  EMC
 *
 * =====================================================================================
 */

#ifndef _CL_TIMER_SERVICE_HXX_
#define _CL_TIMER_SERVICE_HXX_

#include <list>
#include <memory> 
#include "cl_id.hxx"
#include "cl_callback.hxx"
#include "cl_timestamp.hxx"

namespace neo
{
class CLTimestamp;
class CLTimer;
class CLLock;
class CLChannel;

class CLTimerService
{
public:
  CLTimerService();
  ~CLTimerService();
	CLId schedule(const CLCallbackFunctor& timerCallback,
			          const CLTimestamp& when,
                int msecsInterval);
  void removeTimer(const CLId& timerId);
	CLChannel* timerChannel(void) const;
	const CLTimestamp& nextExpiredTime(void) const
	{
		return m_cachedNextExpiredTime;
	}

private:
  CLTimerService(const CLTimerService&);
  CLTimerService& operator=(const CLTimerService&);

private:
	typedef std::shared_ptr<CLTimer> TimerSPtr;
  typedef std::list<TimerSPtr> TimerList;

private:
  void exec(void);
  bool doAddTimerWithHoldLock(const TimerSPtr& aTimer);
  bool doRemoveTimerWithHoldLock(const CLId& timerId);
  void resetTimerfd(const CLTimestamp& ts);
  void addTimer(const TimerSPtr& aTimer);

private:
  int m_timerfd;
  std::unique_ptr<CLLock> m_lock;
  std::unique_ptr<CLChannel> m_timerChannel;
  TimerList m_timers;
  CLTimestamp m_cachedNextExpiredTime;
};

} // neo

#endif //_CL_TIMER_SERVICE_HXX_

